// pages/userInfo/viewed/viewed.js
const app = getApp()

Page({
  data: {
    viewedList: [],
    loading: false,
    picLocal: app.globalData.picLocal,
    baseHeadPic: app.globalData.picLocal + '/default/head/head.png'
  },

  onLoad() {
    this.loadData()
  },

  onShow() {
    this.loadData()
  },

  getStorageKey() {
    const user = wx.getStorageSync('userInfo')
    return user && user.id ? `viewHistory_${user.id}` : 'viewHistory_guest'
  },

  loadData() {
    this.setData({ loading: true })
    const rawList = wx.getStorageSync(this.getStorageKey()) || []
    const list = rawList.map(item => ({
      ...item,
      viewedAtText: this.formatTime(item.viewedAt)
    }))
    this.setData({
      viewedList: list,
      loading: false
    })
    wx.stopPullDownRefresh()
  },

  clearHistory() {
    if (!this.data.viewedList.length) {
      return
    }
    wx.showModal({
      title: '清空浏览记录',
      content: '确定要清空所有浏览记录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync(this.getStorageKey())
          this.setData({ viewedList: [] })
        }
      }
    })
  },

  viewHouseDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/index/houseInfo/houseInfo?id=${id}`
    })
  },

  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp)
    if (Number.isNaN(date.getTime())) return ''
    const y = date.getFullYear()
    const m = `${date.getMonth() + 1}`.padStart(2, '0')
    const d = `${date.getDate()}`.padStart(2, '0')
    const h = `${date.getHours()}`.padStart(2, '0')
    const mm = `${date.getMinutes()}`.padStart(2, '0')
    return `${y}-${m}-${d} ${h}:${mm}`
  },

  onPullDownRefresh() {
    this.loadData()
  }
})

